<template>
  <el-container>
    <my-theme-card>
      <el-header class="cu-header">
        <el-button type="primary" class="cu-button" icon="el-icon-plus" size="mini" @click="addRootMenuClick">新增根节点</el-button>
      </el-header>

      <el-main>
        <el-row>
          <el-col :span="5">
            <div class="grid-content bg-purple">
              <el-card class="box-card">
                <el-tree
                  :data="trees"
                  :props="defaultProps"
                  :render-content="renderContent"
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick"
                />
              </el-card>
            </div>
          </el-col>

          <el-col :span="18" :offset="1"><div class="grid-content bg-purple-light">
            <el-card class="box-card">
              <el-collapse v-model="activeName" accordion>
                <el-collapse-item title="菜单信息" name="1">
                  <el-form ref="form" :model="currentMenu" label-width="80px">
                    <el-form-item label="ID">
                      <el-input v-model="currentMenu.id" disabled />
                    </el-form-item>
                    <el-form-item label="父级ID">
                      <el-input v-model="currentMenu.pid" />
                    </el-form-item>
                    <el-form-item label="名称">
                      <el-input v-model="currentMenu.name" />
                    </el-form-item>
                    <el-form-item label="菜单显示的标题">
                      <el-input v-model="currentMenu.title" />
                    </el-form-item>
                    <el-form-item label="url地址">
                      <el-input v-model="currentMenu.url" />
                    </el-form-item>
                    <el-form-item label="排序">
                      <el-input v-model="currentMenu.zindex" />
                    </el-form-item>
                    <el-form-item label="组件">
                      <el-input v-model="currentMenu.component" />
                    </el-form-item>
                    <el-form-item label="图标">
                      <el-input v-model="currentMenu.icon" />
                    </el-form-item>
                    <el-form-item label="路径">
                      <el-input v-model="currentMenu.path" />
                    </el-form-item>
                    <el-form-item label="跳转地址">
                      <el-input v-model="currentMenu.redirect" />
                    </el-form-item>
                    <el-form-item label="是否隐藏">
                      <el-select v-model="currentMenu.hidden" placeholder="请选择">
                        <el-option
                          v-for="item in dir_logic"
                          :key="item.id"
                          :label="item.label"
                          :value="item.data"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="是否缓存">
                      <el-select v-model="currentMenu.noCache" placeholder="请选择">
                        <el-option
                          v-for="item in dir_logic"
                          :key="item.id"
                          :label="item.label"
                          :value="item.data"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button v-if="currentMenu.id" type="primary" @click="editTask">提交修改</el-button>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
                <el-collapse-item title="菜单权限" name="2">
                  <div>控制反馈：通过界面样式和交互动效让用户可以清晰的感知自己的操作；</div>
                  <div>页面反馈：操作后，通过页面元素的变化清晰地展现当前状态。</div>
                </el-collapse-item>
                <el-collapse-item title="菜单角色" name="3">
                  <div>
                    <el-col :span="1"><div class="grid-content bg-purple-light">
                      <el-button v-if="(currentMenu && currentMenu.id)" class="table-header-btn" type="primary" icon="el-icon-plus" size="mini" @click="addMenuRolesClick">新增</el-button>
                    </div></el-col>
                    <template>
                      <el-table :data="roles" stripe border style="width: 100%">
                        <el-table-column prop="name" label="角色名称" width="180" />
                        <el-table-column prop="code" label="角色唯一编码" />
                        <el-table-column prop="description" label="角色描述" width="180" />
                      </el-table>
                    </template>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </div></el-col>
        </el-row>
      </el-main>

      <el-dialog :title="form.title" :visible.sync="dialogFormVisible" label-width="110px" :close-on-click-modal="false" center append-to-body>
        <el-form :model="tempMenu" label-width="110px" :inline="true">
          <el-form-item label="父级ID">
            <el-input v-model="tempMenu.pid" :disabled="form.pid" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="tempMenu.name" />
          </el-form-item>
          <el-form-item label="菜单显示的标题">
            <el-input v-model="tempMenu.title" />
          </el-form-item>
          <el-form-item label="url地址">
            <el-input v-model="tempMenu.url" placeholder="views/system/role/index" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="tempMenu.zindex" />
          </el-form-item>
          <el-form-item label="组件">
            <el-input v-model="tempMenu.component" placeholder="layout或-" />
          </el-form-item>
          <el-form-item label="图标">
            <el-input v-model="tempMenu.icon" />
          </el-form-item>
          <el-form-item label="路径">
            <el-input v-model="tempMenu.path" placeholder="/bengbeng" />
          </el-form-item>
          <el-form-item label="跳转地址">
            <el-input v-model="tempMenu.redirect" />
          </el-form-item>
          <el-form-item label="菜单是否隐藏">
            <el-select v-model="tempMenu.hidden" placeholder="请选择">
              <el-option
                v-for="item in dir_logic"
                :key="item.id"
                :label="item.label"
                :value="item.data"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="菜单是否隐藏">
            <el-select v-model="tempMenu.noCache" placeholder="请选择">
              <el-option
                v-for="item in dir_logic"
                :key="item.id"
                :label="item.label"
                :value="item.data"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTask">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="删除确认"
        :visible.sync="dialogConfirmVisible"
        :close-on-click-modal="false"
        width="30%"
        append-to-body
        center
      >
        <span>{{ deleteMessage }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogConfirmVisible = false">取 消</el-button>
          <el-button type="danger" @click="deleteMenusTask">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="form.title" :visible.sync="dialogRolesVisible" :close-on-click-modal="false" center append-to-body>
        <role-list @roleListClose="closeRolesDialog" />
      </el-dialog>
    </my-theme-card>
  </el-container>
</template>

<style scoped>
 .cu-aside {
   width:500px;
   height:100%;
 }
 .cu-header {

 }
 cu-main {
   background: #eef1f6;
 }
 .cu-button {
   margin:15px 15px 15px 0px;
 }
</style>

<script>
import request from '@/utils/request'
const roleList = () => import('@/components/RoleList/index')
import { remove, isArray } from 'lodash'
export default {
  components: {
    roleList
  },
  data() {
    return {
      activeName: '1',
      dialogFormVisible: false,
      dialogConfirmVisible: false,
      dialogRolesVisible: false,
      form: {
        pid: false,
        title: '添加菜单'
      },
      deleteMessage: '确认删除该菜单吗？',
      tempMenu: {
        zindex: 0
      },
      currentMenu: {},
      deleteMenus: [],
      menus: [],
      roles: [],
      chooseRolesTemp: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    trees: function() {
      const menus = this.menus
      // 1.取出pid为根目录的菜单
      const root_menu = remove(menus, (menu) => {
        return menu.pid === '0'
      })
      // 2.进行递归
      this.recursiveMenuArray(root_menu, menus)
      return root_menu
    },
    dir_logic: function() {
      return this.$store.state.directory.directory['logic']
    },
    key_logic: function() {
      const { logic = {}} = this.$store.state.directory.directoryItem
      return logic
    }
  },
  watch: {
    'tempMenu.name': function() {
      this.tempMenu.title = this.tempMenu.name
    }
  },
  created() {
    this.directoryUpdate()
    this.query()
  },
  methods: {
    // 字典更新
    directoryUpdate: function() {
      this.$store.commit('directory/setDirectory', 'logic')
    },
    // 添加根节点菜单事件
    addRootMenuClick: function() {
      this.form.title = '添加根节点'
      this.form.pid = true
      this.tempMenu.pid = 0
      this.dialogFormVisible = true
    },
    // 关闭
    closeRolesDialog: function(data) {
      if (data && data.length > 0) {
        this.chooseRolesTemp = []
        data.forEach(item => {
          this.chooseRolesTemp.push({
            id: item
          })
        })
      }
      this.dialogRolesVisible = false
      this.updateMenuRolesTask()
    },
    // tree节点点击事件
    handleNodeClick: function(data) {
      this.currentMenu = data
      this.queryRolesByMenu()
    },
    addTask: function() {
      this.$progress.start()
      request({
        url: '/system/menu/addMenu',
        method: 'post',
        data: this.tempMenu
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.dialogFormVisible = false
          this.query()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { this.$progress.done() })
    },
    // menu编辑
    editTask: function() {
      const loadingInstance = this.Loading.service()
      request({
        url: '/system/menu/editMenu',
        method: 'post',
        data: this.currentMenu
      }).then(res => {
        loadingInstance.close()
        if (res.result) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { loadingInstance.close() })
    },
    deleteMenusTask: function() {
      this.$progress.start()
      request({
        url: '/system/menu/deleteMenus',
        method: 'post',
        data: {
          menus: this.deleteMenus
        }
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.dialogConfirmVisible = false
          this.query()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { this.$progress.done() })
    },
    // menu查询
    query: function() {
      this.$progress.start()
      request({
        url: '/system/menu/query',
        method: 'post',
        data: {
          current: 1,
          size: 9999,
          orders: [
            { field: 'pid' }, { field: 'zindex' }
          ]
        }
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.$message.success(res.msg)
          this.menus = res.data.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { this.$progress.done() })
    },
    // 查询该菜单的关联角色
    queryRolesByMenu: function() {
      if (this.currentMenu) {
        request({
          url: '/system/menu/queryRolesByMenu',
          method: 'post',
          data: this.currentMenu
        }).then(res => {
          this.roles = res.data
        })
      }
    },
    // 添加该菜单和角色的关联
    addMenuRolesClick: function() {
      this.dialogRolesVisible = true
    },
    updateMenuRolesTask: function() {
      this.$progress.start()
      request({
        url: '/system/menu/updateMenuRoles',
        method: 'post',
        data: {
          menu: this.currentMenu,
          roles: this.chooseRolesTemp
        }
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.$message.success(res.msg)
          this.queryRolesByMenu()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { this.$progress.done() })
    },
    // 递归菜单数组转为tree
    recursiveMenuArray: function(roots, menus) {
      const that = this
      roots.forEach(root => {
        root.children = remove(menus, function(menu) {
          return menu.pid === root.id
        })
        // 如果还有剩下的
        if (menus && menus.length > 0) {
          that.recursiveMenuArray(root.children, menus)
        }
      })
    },
    // 递归菜单tree转为数组
    recursiveMenuTree: function(menus, trees) {
      const that = this
      if (isArray(trees)) {
        trees.forEach(tree => {
          menus.push(tree)
          if (tree.children && tree.children.length > 0) {
            that.recursiveMenuTree(menus, tree.children)
          }
        })
      } else {
        menus.push(trees)
        if (trees.children && trees.children.length > 0) {
          that.recursiveMenuTree(menus, trees.children)
        }
      }
    },
    // 菜单添加事件
    append: function(data) {
      this.tempMenu.pid = data.id
      this.form.pid = true
      this.form.title = '添加子菜单'
      this.dialogFormVisible = true
    },
    // 菜单移除事件
    remove: function(node) {
      const menus = []
      this.recursiveMenuTree(menus, node.data)
      if (menus.length > 0) {
        if (menus.length <= 1) {
          this.deleteMessage = '确认删除该菜单吗？'
        } else {
          this.deleteMessage = '确认删除该菜单及其子菜单吗？'
        }
        this.deleteMenus = menus
        this.dialogConfirmVisible = true
      } else {
        this.$message.warning('没有查找到需要删除的菜单')
      }
    },
    // tree操作
    renderContent(h, { node, data, store }) {
      return (
        <span style='flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;'>
          <span>
            <span>{node.label}</span>
          </span>
          <span>
            <el-button style='font-size: 12px;' type='text' icon='el-icon-plus' on-click={ () => this.append(data) }>添加</el-button>
            <el-button style='font-size: 12px;' type='text' on-click={ () => this.remove(node, data) }>删除</el-button>
          </span>
        </span>)
    }
  }
}
</script>
